<template>
	<view class="page">
		<view class="title">
			为了更好的为您服务，请您务必填写真实信息
		</view>
		<u-form-item borderBottom v-if="reject_msg">
			<template #label class="title">
				<span style="color: red;">*</span>
				<span style="margin-right: 20rpx;font-weight: bold;">驳回原因:</span>
			</template>
			<u--input v-model="reject_msg" readOnly="readOnly" border="none" placeholder="请输入详细地址"></u--input>
		</u-form-item>
		
		<view class="form">
			<u-form labelPosition="left" :model="customAdvertising" :rules="rules" labelWidth="auto" ref="uForm">
				<!-- <u-form-item borderBottom @click="showLeasingManager = true">
					<template #label class="title">
						<span style="color: red;">*</span>
						<span style="margin-right: 20rpx;font-weight: bold;">投放挡位:</span>
					</template>
					<u-input v-model="customAdvertising.gearPosition" border="none" disabled disabledColor="#ffffff"
						placeholder="请选择投放挡位"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item borderBottom>
					<template #label class="title" v-if="show">
						<span style="color: red;">*</span>
						<span style="margin-right: 20rpx;font-weight: bold;">价格:</span>
					</template>
					<u-input v-model="customAdvertising.price" border="none"></u-input>
				</u-form-item>
				<u-form-item borderBottom v-if="show">
					<template #label class="title">
						<span style="color: red;">*</span>
						<span style="margin-right: 20rpx;font-weight: bold;">剩余位置:</span>
					</template>
					<u-input v-model="customAdvertising.remainingPositions" border="none"></u-input>
				</u-form-item> -->

				<u-form-item borderBottom labelPosition="top">
					<template #label class="title">
						<span style="color: red;">*</span>
						<span style="margin-right: 20rpx;font-weight: bold;">广告标题及广告主图:</span>
					</template>
					<view class="" style=" margin: 20rpx 0;">
						<u--textarea v-model="customAdvertising.advertisingTitle" placeholder="请输入广告标题及内容"
							border="bottom"></u--textarea>

					</view>
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="1" :previewFullImage="true"></u-upload>
				</u-form-item>
				<u-form-item borderBottom labelPosition="top">
					<template #label class="title">
						<span style="color: red;">*</span>
						<span style="margin-right: 20rpx;font-weight: bold;">视频文件:</span>
					</template>
					<u-upload  :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" multiple
						:maxCount="1" accept="video"></u-upload>
						
					</u-upload>
				</u-form-item>
				<u-form-item borderBottom labelPosition="top">
					<template #label class="title">
						<span style="color: red;">*</span>
						<span style="margin-right: 20rpx;font-weight: bold;">广告详情:</span>
					</template>
					<u--textarea v-model="customAdvertising.advertisingDesc" placeholder="请输入详情介绍"></u--textarea>
				</u-form-item>
				<u-form-item labelPosition="top">
					<template #label class="title">
						<span style="color: red;">*</span>
						<span style="margin-right: 20rpx;font-weight: bold;">详情图片(最多上传6张):</span>
					</template>
					<u-upload :fileList="fileList3" @afterRead="afterRead" @delete="deletePic" name="3" multiple
						:maxCount="10" :previewFullImage="true"></u-upload>
				</u-form-item>
			</u-form>
			
		</view>
		
		<view class=""
			style="width: 100%;height: 180rpx; border-top: #555555 solid 1rpx; background-color: #fff;">
			<u-row gutter="10" customStyle="height:100%">
				<u-col span="6" align="center" justify="center">
					<view style="margin: 0 20rpx 0;" v-if="!status">
						<u-button type="primary" shape="circle" text="添加" size="large" :plain="true"
							@click="submit"></u-button>
					</view>
					<view style="margin: 0 20rpx 0;" v-if="status == 2||status == 3">
						<u-button type="primary" shape="circle" text="修改" size="large" :plain="true"
							@click="submit"></u-button>
					</view>
					
					<view style="margin: 0 20rpx 0;" v-if="status">
						<u-button type="primary" shape="circle" text="删除" size="large" :plain="true"
							@click="delad"></u-button>
					</view>
					
				</u-col>
				
			</u-row>
		</view>
		<!-- <u-picker :show="showLeasingManager" :columns="actions" @close="showLeasingManager = false"
			@confirm="confirm"></u-picker> -->


	</view>
</template>

<script>
	import {
		addAdvertisementHome,
		uploadImg,
		delAdvertisementHome,
		uploadVideo
	} from '@/config/api.js';
	export default {
		data() {
			return {
				status: null,
				fileList3:[],
				fileList1:[],
				fileList2: [],
				reject_msg: '',
				show: false,
				showLeasingManager: false,
				actions: [
					['1', '2', '3']
				],
				priceMapping: {
					'1': 10000,
					'2': 5000,
					'3': 1000
				},
				setting: {
					'1': 5,
					'2': 50,
					'3': 1000
				},
				rules: {
					'userInfo.name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'userInfo.sex': {
						type: 'string',
						max: 1,
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
				},
				radio: '',
				id: null,
				switchVal: false,

				// 商户类型
				rowData: null,
				// 自定义广告
				customAdvertising: {
					gearPosition: '',
					price: '',
					remainingPositions: '',
					advertisingTitle: '',
					logo: [],
					videoFile: null,
					advertisingDesc: '',
					descriptPicture: null
				},

			}
		},
		onLoad(option) {
			console.log(option);
			this.rowData = option;
			if(option.id)this.init();
			uni.setNavigationBarTitle({
				title: "新加广告"
			});
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			init(){
				const data = uni.getStorageSync('adInfo');
				this.rowData.nav_id = data.nav_id;
				this.id = data.id;
				this.rowData.store_id = data.store_id;
				this.customAdvertising.advertisingTitle = data.title;
				this.customAdvertising.advertisingDesc = data.context;
				this.fileList1 = [{url: data.title_img}]
				this.fileList2 = [{url: data.video}]
				this.reject_msg = data.reject_msg;
				this.status = data.status;
				data['img_list'].split(',').forEach(el => {
					this.fileList3.push({url:el})
				})
			},
			showvideo(){
				console.log(23121)
			},
			// 图片上传
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					let result = null;
					if (lists[i].type == 'video') result = await this.uploadFileVideoe(lists[i].url);
					if (lists[i].type == "image") result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFileVideoe(url) {
				return new Promise((resolve, reject) => {
					uploadVideo({
						url: url,
						fileName: 'auctionOmpany_ad'
					}).then(res => {
						resolve(res)
					})
				})
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uploadImg({
						url: url,
						fileName: 'auctionOmpany_ad'
					}).then(res => {
						resolve(res)
					})
				})
			},
			confirm(e) {
				const selectedProxyType = e.value;
				this.customAdvertising.gearPosition = selectedProxyType;
				this.customAdvertising.price = this.priceMapping[selectedProxyType] || '0'; // 设置入驻费，若未匹配则默认为0
				this.customAdvertising.remainingPositions = this.setting[selectedProxyType] || '0';
				this.show = true;
				this.showLeasingManager = false;
			},
			onClickItem(e) {
				console.log(e);
				this.current = e.currentIndex
			},
			add() {
				this.dynamicFormData.domains.push({
					label: '域名',
					value: '',
					rules: [{
						'required': true,
						errorMessage: '域名项必填'
					}],
					id: Date.now()
				})
			},
			delad(id) {
				const _this = this;
				uni.showModal({
					title: '确认删除？',
					success: function(res) {
						if (res.confirm) {
							delAdvertisementHome({id: _this.id}).then(res => {
								uni.$u.toast('成功!')
							})
						}
					}
				});
				
			},
			submit(ref) {
				const sendata = {
					nav_id:this.rowData.nav_id,
					store_id:this.rowData.store_id,
					title: this.customAdvertising.advertisingTitle,
					title_img :this.fileList1[0]['url'],
					video:this.fileList2[0]['url'],
					context:this.customAdvertising.advertisingDesc
				}
				const imglist = [];
				this.fileList3.forEach(el => {
					imglist.push(el.url)
				})
				sendata['img_list'] = imglist.join();
				if(this.id){
					sendata['id'] = this.id;
					sendata['reject_msg'] = '';
					sendata['status'] = 2;
				}
				
				addAdvertisementHome(sendata).then(data => {
					if(data.signType){
						wx.requestPayment({
						  timeStamp: data.timeStamp,
						  nonceStr: data.nonceStr,
						  package: data.package,
						  signType: data.signType,
						  paySign: data.paySign,
						  success (res) { 
							  console.log(res,'=============')
							  uni.$u.toast('审核中...')
						  },
						  fail (res) { 
							  // 支付失败 删除商品
							  delNameById({'sql_name': data._sql_name,idx: data._idx,order_sn: data._order_sn})
						  }
						})
					}else{
						uni.$u.toast('审核中...')
					}
				})
				// this.$refs[ref].validate().then(res => {
				// 	console.log('success', res);
				// 	uni.showToast({
				// 		title: `校验通过`
				// 	})
				// }).catch(err => {
				// 	console.log('err', err);
				// })
			},
		}
	}
</script>

<style lang="scss">
	.form {

		padding: 0 20rpx;

	}

	.title {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		align-items: center;
		background-color: #ffebeb;
		color: red;
		padding: 0 20rpx;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}
</style>